package project.simulation.listeners;

import java.util.HashMap;
import java.util.Map;

import project.events.packageEvents.PackageCreatedEvent;
import project.events.packageEvents.PackageDeliveredEvent;
import project.events.truckEvents.TruckFollowedRoadEvent;
import framework.events.Event;
import framework.events.EventBroker;
import framework.events.EventListener;

public class TruckListener implements EventListener{

	private Map<Integer,Long> truckDistances;
	private int nrOfPackagesCreated;
	private int nrOfPackagesDelivered;
	private long time = System.currentTimeMillis();
	
	public TruckListener(){
		truckDistances = new HashMap<Integer, Long>();
		nrOfPackagesCreated = 0;
		nrOfPackagesDelivered = 0;
		EventBroker.getEventBroker().register(this);
	}
	
	@Override
	public void handleEvent(Event event) {
		if(event instanceof TruckFollowedRoadEvent){
			TruckFollowedRoadEvent e = (TruckFollowedRoadEvent) event;
			this.handleTruckFollowedRoadEvent(e);
		}
		else if(event instanceof PackageCreatedEvent){
			PackageCreatedEvent e = (PackageCreatedEvent) event;
			this.handlePackageCreatedEvent(e);
		}
		else if(event instanceof PackageDeliveredEvent){
			PackageDeliveredEvent e = (PackageDeliveredEvent) event;
			this.handlePackageDeliveredEvent(e);
		}
		
	}

	private void handlePackageDeliveredEvent(PackageDeliveredEvent e) {
		nrOfPackagesDelivered++;
		if(getNrOfPackagesDelivered() == getNrOfPackagesCreated()){
			printDistances();
			System.out.println("Rekentijd : " + (System.currentTimeMillis() - time) + " ms");
			System.out.println("gedaan");
		}
	}

	private void handlePackageCreatedEvent(PackageCreatedEvent e) {
		nrOfPackagesCreated++;		
	}

	private void handleTruckFollowedRoadEvent(TruckFollowedRoadEvent e) {
		long newDistance = 0;
		if(truckDistances.containsKey(e.getId())){
			newDistance = truckDistances.get(e.getId()).longValue() + e.getFollowedRoad().getLength();
		}
		else{
			newDistance = e.getFollowedRoad().getLength();
		}
		truckDistances.put(e.getId(),newDistance);
	}

	private void printDistances(){
		long total = 0;
		for(Integer truck : truckDistances.keySet()){
			total += truckDistances.get(truck);
			System.out.println("total distance travelled by truck " + truck + " = " + truckDistances.get(truck));
		}
		System.out.println("total distance travelled by all trucks = " + total);
	}
	
	
	public int getNrOfPackagesCreated() {
		return nrOfPackagesCreated;
	}

	public void setNrOfPackagesCreated(int nrOfPackagesCreated) {
		this.nrOfPackagesCreated = nrOfPackagesCreated;
	}

	public int getNrOfPackagesDelivered() {
		return nrOfPackagesDelivered;
	}

	public void setNrOfPackagesDelivered(int nrOfPackagesDelivered) {
		this.nrOfPackagesDelivered = nrOfPackagesDelivered;
	}
	
	@Override
	public void terminate() {
		// TODO Auto-generated method stub
		
	}

}
